# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: jaewon

import gzip
import logging
import sys

from absl import app, flags

from coin.base.datetime_util import to_datetime
from coin.strategy.marketsim.tool.result_util import read_sim_result


def open_outfile_from_flag():
  outfile = flags.FLAGS.out
  if outfile is None:
    return sys.stdout
  if outfile.endswith('.gz'):
    return gzip.open(outfile, 'w')
  return open(outfile, 'w')


def main(args):
  if len(args) <= 1:
    sys.stderr.write('Usage: %s <files...>')
    return 1

  results = read_sim_result(sorted(args[1:]))
  executions = []
  for file, result in results.items():
    executions.extend(result.executions)

  with open_outfile_from_flag() as f:
    for e in executions:
      record = '--- %s\n%s\n' % (to_datetime(e.exec_ts), e)
      f.write(record.encode('utf-8'))

  return 0


if __name__ == '__main__':
  logging.basicConfig(
      level='DEBUG',
      format='%(levelname)8s %(asctime)s %(name)s %(filename)s:%(lineno)d] %(message)s')

  flags.DEFINE_string(
      'out',
      None,
      'If specified, writes to the file. If the extension is `.gz`, makes gzipped file.')

  app.run(main)
